import React, { useEffect, useState } from 'react';
import { Descriptions, Button, Modal, Form, Input, message } from 'antd';
import request from 'umi-request';

function Info(props) {
  const account = window.JSON.parse(sessionStorage.getItem('account'));
  let [data, setData] = useState({});

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = (values) => {
    setIsModalVisible(false);
    values = form.getFieldsValue();
    console.log(values);
    request
      .post('http://123.60.20.244:8080/atm/account/changeUserInfo', {
        params: {
          u_tel: values.u_tel,
          id_number: values.id_number,
          user_name: account.user_name,
        },
      })
      .then((response) => {
        if (response.code === 0) {
          message.success({
            content: '修改成功',
            key: 'global_key',
            duration: 2,
          });
          getUserInfo();
          return Promise.reject();
        } else {
          message.error({
            content: '修改失败',
            key: 'global_key',
            duration: 2,
          });
          return Promise.reject();
        }
      });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const getUserInfo = () => {
    request
      .get('http://123.60.20.244:8080/atm/account/getUserInfo', {
        params: {
          user_name: account.user_name,
        },
      })
      .then((response) => {
        setData((data = response.account));
      });
  };

  useEffect(async () => {
    getUserInfo();
  }, []);

  return (
    <div>
      <Descriptions title="用户信息">
        <Descriptions.Item label="用户ID">{data.a_id}</Descriptions.Item>
        <Descriptions.Item label="电话">{data.u_tel}</Descriptions.Item>
        <Descriptions.Item label="身份证号码">
          {data.id_number}
        </Descriptions.Item>
        <Descriptions.Item label="账户余额">{data.balance}</Descriptions.Item>
      </Descriptions>
      <Button onClick={showModal}>修改信息</Button>
      <Modal
        title="请修改你的信息"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form}>
          <Form.Item name="u_tel" label="电话">
            <Input />
          </Form.Item>
          <Form.Item name="id_number" label="身份证号码">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default Info;
